import Taro from '@tarojs/taro'
import { ref } from 'vue'
import { IUserInfo } from './interface'
// Token 相关操作
export const getToken = () => Taro.getStorageSync('token')
export const setToken = (token: string) => Taro.setStorageSync('token', token)
export const removeToken = () => Taro.removeStorageSync('token')

export const useAuth = () => {
    const isLogin = ref(false)
    const userInfo = ref<IUserInfo | null>(null)
    const isAdmin = ref(false)

    // 检查登录状态
    const checkLoginStatus = () => {
        isLogin.value = !!getToken()
    }

    // 设置用户信息
    const setUserInfo = (info: any) => {
        Taro.setStorageSync('nickName', info.nickName)
        Taro.setStorageSync('avatar', info.avatar)
        Taro.setStorageSync('level', info.level)
    }

    // 获取用户信息
    const getUserInfo = () => {
        userInfo.value = {
            nickName: Taro.getStorageSync('nickName') || '',
            avatar: Taro.getStorageSync('avatar') || '',
            level: Taro.getStorageSync('level') || ''
        }
        isAdmin.value = userInfo.value.level === 'admin'
    }

    // 跳转登录页
    const toLogin = () => {
        Taro.navigateTo({
            url: '/pages/login/index'
        })
    }

    // 登出
    const logout = () => {
        removeToken()
        isLogin.value = false
    }

    // 监听登录状态变化
    const setupLoginListener = () => {
        Taro.useDidShow(() => {
            checkLoginStatus()
            if (isLogin.value) {
                getUserInfo()
            }
        })
    }

    setupLoginListener()

    return {
        isLogin,
        userInfo,
        isAdmin,
        setUserInfo,
        getUserInfo,
        toLogin,
        logout
    }
}
